import axios from "axios";
import React, { useEffect, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { Flex, Button, Popup, Cell, NavBar, Dialog } from "react-vant";
import { Address, ListItem } from "../../components";
import { useAppDispatch, useAppSelector } from "../../store/hooks";
import {
  closeOrderActionCreator,
  OrderDetail,
} from "../../store/user/userReducer";
import { Map, Marker, NavigationControl, InfoWindow } from "react-bmapgl";

const Index: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const location = useLocation();
  const { id } = useParams();
  const orderList = useAppSelector((v) => v.user.orderList);
  const v = orderList.find((v) => v.id === id) as OrderDetail;
  const [str, setStr] = useState("00:00:00");
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  useEffect(() => {
    let timer: NodeJS.Timer;
    if (v.state === "待付款") {
      timer = setInterval(() => {
        const time =
          1000 * 60 * 60 * 2 - (new Date().getTime() - v.createDateTime);
        if (time < 0) {
          clearInterval(timer);
          dispatch(closeOrderActionCreator(v));
          return;
        }

        const s = Math.floor((time / 1000) % 60)
          .toString()
          .padStart(2, "0");
        const m = Math.floor((time / 1000 / 60) % 60)
          .toString()
          .padStart(2, "0");
        const h = Math.floor((time / 1000 / 60 / 60) % 24)
          .toString()
          .padStart(2, "0");
        setStr(`${h}:${m}:${s}`);
      }, 1000);
    }

    return () => {
      clearInterval(timer);
    };
  }, []);

  const payment = async () => {
    // 调用支付宝
    const resp = await axios.post("/api/pay", {
      id: v.id,
      price: v.price,
      title: v.title,
    });
    window.location.href = resp.data.data;
  };

  const back = () => {
    if (v.state === "待付款")
      Dialog.confirm({
        title: "警告",
        message: "当前有订单未付款， 确认要离开吗？",
      })
        .then(() => {
          navigate(-1);
        })
        .catch(() => {});
    else navigate(-1);
  };

  return (
    <div>
      <NavBar title="订单详情" onClickLeft={() => back()}></NavBar>
      <div style={{ padding: 6 }}>
        <Flex style={{ margin: "10px 0" }} align="center">
          <Flex.Item>订单编号:</Flex.Item>
          <Flex.Item>{v.id}</Flex.Item>
        </Flex>
        <Flex style={{ margin: "10px 0" }} align="center">
          <Flex.Item>订单金额:</Flex.Item>
          <Flex.Item>{v.price}</Flex.Item>
        </Flex>
        <Flex style={{ margin: "10px 0" }} align="center">
          <Flex.Item>订单标题:</Flex.Item>
          <Flex.Item>{v.title}</Flex.Item>
        </Flex>
        <Address
          {...v.addressDetail}
          onClick={() =>
            navigate("/select/address", {
              state: { address: v.addressDetail, id: v.id },
            })
          }
        ></Address>
        <div>
          <Map
            center={v.addressDetail.pos}
            zoom="14"
            style={{ height: 200 }}
            enableDragging={false}
          >
            <InfoWindow
              position={v.addressDetail.pos}
              text={v.addressDetail.address}
              title="地址"
            />
          </Map>
        </div>
        <div className="card-item">
          <div className="card-content">
            <div className="list">
              {v.projects.map((v) => {
                return (
                  <div key={v.id} style={{ padding: 10 }}>
                    <ListItem {...v}></ListItem>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        {v.state === "待付款" && (
          <div>
            <h3 style={{ color: "red", textAlign: "center" }}>
              距离订单失效还剩{str}
            </h3>
            <Button
              type="primary"
              square
              block
              onClick={() => setVisible(true)}
              style={{ margin: "4px 0" }}
            >
              立即支付
            </Button>
            <Button
              type="danger"
              square
              block
              onClick={() => dispatch(closeOrderActionCreator(v))}
              style={{ margin: "4px 0" }}
            >
              取消订单
            </Button>
          </div>
        )}

        {v.state === "待收货" && <div>物流信息</div>}
        {v.state === "已关闭" && <div>订单已关闭</div>}
      </div>

      <Popup
        visible={visible}
        onClose={() => setVisible(false)}
        position="bottom"
      >
        <div style={{ padding: "10px" }}>
          <Cell.Group>
            <Cell title="支付宝" onClick={() => payment()} isLink />
          </Cell.Group>
        </div>
      </Popup>
    </div>
  );
};

export default Index;
